<?php

namespace app\shop\model\user;

use app\common\model\user\Grade as GradeModel;
use app\shop\model\user\User as UserModel;

/**
 * 用户会员等级模型
 */
class Grade extends GradeModel
{
    /**
     * 获取列表记录
     */
    public function getList($data)
    {
        return $this->where('is_delete', '=', 0)
            ->order(['weight' => 'asc', 'create_time' => 'asc'])
            ->append(['condition'])
            ->paginate($data);
    }




    /**
     * 新增记录
     */
    public function add($data)
    {
        //是否存在相同权重等级
        $same_grade = $this->where('weight', '=', $data['weight'])->find();
        if ($same_grade) {
            $this->error = '权重等级不能重复';
            return false;
        }
        $data['app_id'] = self::$app_id;
        $data['is_default'] = 0;
        return $this->save($data);
    }

    /**
     * 编辑记录
     */
    public function edit($data)
    {
        //是否存在相同权重等级
        $same_grade = $this->where('weight', '=', $data['weight'])->find();
        if ($same_grade && $same_grade['grade_id'] != $this['grade_id']) {
            $this->error = '权重等级不能重复';
            return false;
        }
        return $this->save($data);
    }

    /**
     * 软删除
     */
    public function setDelete()
    {
        // 判断该等级下是否存在会员
        if (UserModel::checkExistByGradeId($this['grade_id'])) {
            return false;
        }
        return $this->save(['is_delete' => 1]);
    }

}